using anydata.Entitys;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Text.Json;

namespace anydata.Services
{
    public class ThingConvertService : ITransient
    {
        public List<EntityBase> Converting(IEnumerable data, XForm form)
        {
            var result = new List<EntityBase>();
            foreach (var raw in data)
            {
                if (raw is not EntityBase thing)
                {
                    continue;
                }
                var clone = new EntityBase
                {
                    ["id"] = thing.id,
                    ["name"] = thing.name,
                    ["status"] = thing.status,
                    ["version"] = thing.version,
                    ["isDeleted"] = thing.isDeleted,
                    ["createUser"] = thing.createUser,
                    ["createTime"] = thing.createTime,
                    ["updateUser"] = thing.updateUser,
                    ["updateTime"] = thing.updateTime,
                    ["belongId"] = JToken.FromObject(thing["belongId"])
                };
                foreach (var field in form.fields)
                {
                    var value = thing[field.code];
                    if (value is not null)
                    {
                        switch (field.valueType)
                        {
                            case "选择型":
                            case "分类型":
                                if (field.lookups is not null)
                                {
                                    var lookup = field.lookups.Find(lookup => lookup.value == value.ToString());
                                    if (lookup is not null)
                                    {
                                        clone[field.attr + "_CODE"] = lookup.code;
                                        clone[field.attr + "_NAME"] = lookup.text;
                                    }
                                }
                                break;
                            case "数值型":
                                clone[field.attr] = value as dynamic;
                                break;
                            case "描述型":
                            case "日期型":
                            case "时间型":
                            case "附件型":
                                clone[field.attr] = value.ToString();
                                break;
                        }
                    }
                }
                result.Add(clone);
            }
            return result;
        }
    }
}
